import {Directive, forwardRef} from '@angular/core';
import {NG_VALIDATORS, Validator, AbstractControl, Validators} from "@angular/forms";
import {ValidatorRegexPattern} from "./validator-regex-pattern";

@Directive({
    selector: '[digits][formControlName],[digits][formControl],[digits][ngModel]',
    providers: [
        {provide: NG_VALIDATORS, useExisting: forwardRef(() => DigitsValidator), multi: true}
    ]
})
export class DigitsValidator implements Validator {
    validate(c: AbstractControl): { [key: string]: any } {
        if (Validators.required(c) != undefined) {
            return null;
        }

        let value = c.value;
        if (!value) {
            return null;
        }

        let isValid = ValidatorRegexPattern.digits.test(value);

        return isValid ? null : {
            digits: {
                valid: false
            }
        };
    }
}
